package com.uft.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.uft.dp.HTTPSClient;
import com.uft.model.dao.DPProfileDAO;
import com.uft.model.entity.DPProfile;
import com.uft.model.entity.DPRuntime;

@Service
public class DPService {
	private  static Logger  logger = Logger.getLogger(DPService.class);
	
	@Autowired
	DPProfileDAO dpProfileDAO;
	
	private List<DPProfile> dpProfileList= new ArrayList<DPProfile>();
	@Value("${dpService.cacheCheckInterval:3}") private  int CACHE_CHECK_INTERVAL;
	
	private Calendar lastCacheCheck;
	
	public void updateCache(){
		dpProfileList=dpProfileDAO.getDPProfileList();
		lastCacheCheck=Calendar.getInstance();
	}
	
	@Scheduled(fixedDelayString="${dpService.statistics.fixedDelay:60000}")
 	public void getStatistics(){
 		logger.trace("getStatistics..."+Calendar.getInstance().getTime().toString());
 		if(lastCacheCheck == null){
 			updateCache();
 		}
		Calendar now = Calendar.getInstance();
		long diff = now.getTimeInMillis() - lastCacheCheck.getTimeInMillis();
		if(diff >= CACHE_CHECK_INTERVAL * 60 * 1000){
			updateCache();
		}
		for(DPProfile dpProfile:dpProfileList){
			try {
				
				 
			//	DPHttpsClient httpsClient=new DPHttpsClient(dpProfile.getDpHostname(),
			//			Integer.parseInt(dpProfile.getDpPort()),dpProfile.getDpUsername(), 
			//			dpProfile.getDpPassword());
				if(dpProfile.isEnableStats()){
					 HTTPSClient httpsCleintObj = new HTTPSClient(dpProfile.getDpHostname(), Integer.parseInt(dpProfile.getDpPort()), dpProfile.getDpUsername(), dpProfile.getDpPassword());
					 httpsCleintObj.connect(true);	
					 DPRuntime dpRuntime= httpsCleintObj.getStatics();
					 dpRuntime.setDpName(dpProfile.getDpName());
					 dpRuntime.setDpHostname(dpProfile.getDpHostname());
					 dpProfileDAO.addDPRuntime(dpRuntime);
					 httpsCleintObj.releaseConnection();
				}
				
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
 		 
 	}
	
}
